import { Component, OnInit } from "@angular/core";
import { AxiosService } from "../../axios.service";
import { LocalStorageService } from "src/app/myService/local-storage.service";
import { Router } from "@angular/router";
// import { DatePipe } from '@angular/common';
let timeIndex = 0;
let hour;
let minutes;
let seconds;

@Component({
  selector: "app-emp-design",
  templateUrl: "./emp-design.component.html",
  styleUrls: ["./emp-design.component.scss"],
})
export class EmpDesignComponent implements OnInit {
  isLoading;

  deadline = Date.now();
  //所有工单数据
  public tempData = [];

  public listOfData = []; //工单文件区数据

  fileInfom; //显示工单对应的文件信息
  fileInfom2;
  isOkLoadingfileInfom;

  public fileList; //选择要上传的文件
  uploader;
  fileName; //文件名
  public workName; //下载时需补齐的文件路径
  public link; //下载链接
  workerName; //工件名

  public unionorder: any; //工单号,
  public newValue: any; //"新值"
  name; //"表中栏位名称"

  addRemark1; //编辑设计备注
  addDlyy;
  isOkLoadingRemark;
  designRemark;
  designRemark1;

  isFileVisible; //删除文件信息
  isFileOkLoading;
  id; //文件信息id

  splitJudge: string = ",";

  // 接收要修改的数据
  updateData;
  workData = []; //接受工联单号展开显示的工件信息

  first: any; //首个19码
  tail: any; //结尾19码
  uploadData; // 上传数据
  workOrder; //上传对应的工单号
  sheet_order; //工件上传

  isShow = [];
  btnStop = [];
  btnStart = [];

  value; //计时时间值
  totalTime; //数据库中的时间
  time; //页面的时间
  recordRowClick = -1;

  showWarning = {}; //工件行显示退回图标
  showBigWarning = []; //工单行显示退回图标

  ishowerer = [];
  sfmtime = "00:00:00";
  sjkg = false;
  kssj;
  jsq;
  min = 0;
  dlyy;
  dlyyadd;
  dlyynr;
  dlyysz = [];
  dlyysc = [];
  // 工号
  jobNo;
  imglist;

  // 以下数据用于指派工程师后发送邮件
  engineerJobNo = [];
  engineerMail = [];
  mailParamsForSend = {
    "type": '',
    "WorkOrder": "",
    "factory": "",
    "name": "",
    "machine_type": "",
    "quantity": 0,
    "toolway": "",
    "delivery_date": "",
    "emp": [],
    "empAddress":[]
  };

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    private router: Router
  ) // private datePipe: DatePipe
  { }

  ngOnInit(): void {
    //获取全部数据
    this.getAllData();
  }

  //获取全部数据
  getAllData() {
    this.jobNo = this.storage.getStorageData("user").job_no;
    console.log(this.jobNo);
    this.axios.axiosPost("QueryUnionOrder", {
      stage: 0,
      stageValue: 1,
      status: 0,
      job_no: this.jobNo,
    })
      .then((data) => {
        if (data) {
          this.ishowerer = [];
          // debugger
          console.log(data);
          this.tempData = data["order"];
          console.log(this.tempData);
          // debugger
          for (let i = 0; i < this.tempData.length; i++) {
            // 实际时间栏位把秒转为小时
            this.tempData[i].sheji_shijian =
              Number(this.tempData[i].sheji_shijian) / 3600;
            if (this.tempData[i].sheji_shijian > 0.0) {
              this.tempData[i].sheji_shijian =
                Math.floor((this.tempData[i].sheji_shijian + 0.01) * 100) / 100;
            }

            this.ishowerer.push(false);
            if (this.tempData[i].tip > 0) {
              this.showBigWarning.push(true);
            } else {
              this.showBigWarning.push(false);
            }
          }

          this.storage.setStorageData("result", this.tempData);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  //点击————添加设计备注
  addRemark(item) {
    this.addRemark1 = true;
    this.designRemark = item.design_remark;
    console.log(this.designRemark);
    this.updateData = item;
    console.log(this.updateData);
    this.axios.axiosPost("QueryBeizhuInfo", { name: this.dlyy })
      .then((data) => {
        console.log(data);
        if (data['result'] === 'ok') {
          this.dlyy = data["order"]
          console.log(this.dlyy)
          if (this.designRemark.split(",")) {
            this.dlyysz = this.designRemark.split(",");
            console.log(this.dlyysz)
            for (var i = 0; i < this.dlyysz.length; i++) {
              for (var y = 0; y < this.dlyy.length; y++) {
                if (this.dlyysz[i] == this.dlyy[y].name) {
                  this.dlyy[y].show = true;
                }
              }
            }
          }

        }

      })
      .catch((err) => {
        console.log(err);
      });

  }
  //确认————添加设计备注
  addRemarkOk() {
    this.isOkLoadingRemark = true;
    this.addRemark1 = false;
    this.isOkLoadingRemark = false;
    console.log(this.first);
    this.axios.axiosPost("UpdateUnionOrder", {
      unionorder: this.updateData.union_order,
      name: "design_remark",
      newValue: this.dlyynr,
    })
      .then((data) => {
        console.log(data);
        if (data["result"] === "ok") {
          this.getAllData();
        }
      });
    this.addRemarkCancel();
  }
  //取消————添加设计备注
  addRemarkCancel() {
    this.addRemark1 = false;
  }
  // 删除————添加设计备注
  addRemarkDelete() {
    this.designRemark1 = this.dlyynr.design_remark;
    console.log(this.designRemark1);
    var update;
    update = this.dlyynr;
    console.log(update);
    if (update.split(",")) {
      this.dlyysc = update.split(",");
      console.log(this.dlyysc)
      for (var i = 0; i < this.dlyysc.length; i++) {
        this.axios.axiosPost("DeleteBeizhuInfo", { name: this.dlyysc[i] })
          .then((data) => {
            console.log(data);
            if (data['result'] === 'ok') {
              this.addRemark(this.dlyynr)
            }

          })
          .catch((err) => {
            console.log(err);
          });
      }
    }

  }
  // 点击——添加————添加设计备注
  addRemarkAdd() {
    this.addDlyy = true;
  }
  // 取消——添加————添加设计备注
  addRemarkAddCancel() {
    this.addDlyy = false;
  }
  // 确定——添加————添加设计备注
  addRemarkAddOk() {
    this.addDlyy = false;
    this.axios.axiosPost("AddBeizhuInfo", { name: this.dlyyadd })
      .then((data) => {
        console.log(data);
        if (data['result'] === 'ok') {
          this.addRemark(this.dlyyadd);
          // this.dlyy = data["order"]
          // // this.dlyy.push(this.dlyyadd)
          // console.log(this.dlyy)
        }
      })
      .catch((err) => {
        console.log(err);
      });
    this.addRemarkAddCancel()
    this.dlyyadd = ""
  }





  currentPageDataChange(qqq) { }
  downLoad2(infom) {
    console.log(infom);
    this.fileInfom2 = true;
    this.link = this.axios.domainTest1;
    console.log(this.link);

    if (infom.imagefile) {
      this.imglist = infom.imagefile.split(",");
    } else {
      this.imglist = [];
    }
  }
  CancelShow2() {
    this.fileInfom2 = false;
  }
  ShowOK2() {
    this.fileInfom2 = false;
  }
  CancelShow() {
    this.fileInfom = false;
  }

  //点击图标显示此工单的文件信息
  downLoad(infom) {
    console.log(infom);
    this.fileInfom = true;
    // this.updateData = infom;
    // debugger
    this.workOrder = infom.union_order;
    this.workerName = infom.name;
    this.workName = this.workOrder;
    this.sheet_order = infom.sheet_order;
    console.log(infom.name, this.workOrder);
    if (infom.name !== undefined) {
      this.axios
        .axiosPost("QueryWorkFiles", {
          unionorder: this.workOrder,
          workorder: infom.name,
        })
        .then((data) => {
          console.log(data);
          if (data["result"] === "ok") {
            this.listOfData = data["files"];
          }
        });
    } else if (infom.name === undefined) {
      this.axios
        .axiosPost("QueryWorkFiles", {
          unionorder: this.workOrder,
          workorder: this.sheet_order,
        })
        .then((data) => {
          console.log(data);
          if (data["result"] === "ok") {
            this.listOfData = data["files"];
          }
        });
    }
    
    // 准备邮件格式
    this.mailParamsForSend.type = 'S1';
    this.mailParamsForSend.WorkOrder = infom.union_order;
    this.mailParamsForSend.factory = infom.factory;
    this.mailParamsForSend.name = infom.name;
    this.mailParamsForSend.machine_type = infom.machine_type;
    this.mailParamsForSend.quantity = infom.quatity;
    this.mailParamsForSend.delivery_date = infom.delivery_date;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
    
    // 如果文件数量 = 3 再发邮件
    if (this.listOfData.length == 3) {
       // 发送邮件
       this.axios.axiosPost('SendEmail', this.mailParamsForSend).then((data) => {
        if (data['result'] === 'ok') {
          console.log("SendEmailSuccessfully!");
        }
      }).finally(() => {
        // 每次指定完毕后，重置数组，避免影响下次指定
        this.engineerJobNo = []
        this.engineerMail = []
      })
    }
  }

  //上传文件
  Upload() {
    if (this.uploadData == null) return;
    console.log(this.workOrder, this.workerName);
    if (this.workerName !== undefined) {
      console.log('文件数据：'+this.uploadData);
      this.isLoading = true;
      this.axios
        .axiosPost("Upload", {
          unionorder: this.workOrder,
          workorder: this.workerName,
          filename: this.fileName.files[0]["name"],
          filedata: this.uploadData,
        })
        .then((data) => {
          console.log(data);
          if (data["result"] === "ok") {
            this.isLoading = false;
            alert("上传成功！");
            this.uploadData = null;
            this.axios
              .axiosPost("QueryWorkFiles", {
                unionorder: this.workOrder,
                workorder: this.workerName,
              })
              .then((data) => {
                if (data["result"] === "ok") {
                  this.listOfData = data["files"];
                }
              });
          } else {
            this.isLoading = false;
            alert(data["description"]);
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    } else if (this.workerName === undefined) {
      this.isLoading = true;
      this.axios
        .axiosPost("Upload", {
          unionorder: this.workOrder,
          workorder: this.sheet_order,
          filename: this.fileName.files[0]["name"],
          filedata: this.uploadData,
        })
        .then((data) => {
          console.log(data);
          if (data["result"] === "ok") {
            this.isLoading = false;
            alert("上传成功！");
            this.uploadData = null;
            this.axios
              .axiosPost("QueryWorkFiles", {
                unionorder: this.workOrder,
                workorder: this.sheet_order,
              })
              .then((data) => {
                if (data["result"] === "ok") {
                  this.listOfData = data["files"];
                }
              });
          } else {
            this.isLoading = false;
            alert(data["description"]);
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    }
  }

  //选择要上传的文件名
  openFile(event: any): void {
    this.uploadData = null;
    // debugger
    this.fileName = event.target; //获取点击得到的对象
    const reader = new FileReader();
    reader.onload = () => {
      if (reader.result) {
        this.uploadData = reader.result;
      }
    };
    reader.readAsDataURL(this.fileName.files[0]); //将文件转为Base64格式
    
  }

  handleFileCancel() {
    this.isFileVisible = false;
  }

  downLoadFile(data) {
    console.log(data);
    this.fileName = data.file_name;
    this.link = this.axios.domainTest1 + this.workName + "/" + this.fileName;
    console.log(this.fileName, this.link);
  }

  //删除文件信息
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data);
    this.id = data.id;
  }

  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost("DeleteWorkFile", { id: this.id }).then((data) => {
      console.log(data);
      if (data["result"] === "ok") {
        let listData = this.listOfData.filter((res) => res["id"] !== this.id);
        this.listOfData = listData;
      }
    });
  }

  //  //点击工单号显示CNC
  //  showCNC(item) {
  //       console.log(item)
  //       const data = {};
  //       data['union_order'] = item.union_order;
  //       console.log(data['union_order'])
  //       this.router.navigate(['/CNC', data])
  //         // {queryParams: {refersh: new Date().getTime()}}
  //     }

  //查询工件信息
  collapse(key) {
    console.log("aaaa");
    this.axios
      .axiosPost("QueryWorkOrder", {
        unionorder: this.tempData[key].union_order,
        status: 0,
      })
      .then((data) => {
        console.log(data);
        if (data["result"] === "ok" && data["order"].length > 0) {
          // debugger
          const orderData = data["order"];
          this.workData[key] = orderData;
          const tempArr = [];
          // this.returnData = this.workData[key];
          for (let i = 0; i < orderData.length; i++) {
            if (orderData[i]["remark"] !== "") {
              tempArr.push(true);
            } else {
              tempArr.push(false);
            }
          }
          this.showWarning[key] = tempArr;
          console.log("1111111\n", this.showWarning);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  //点击行显示计时器
  clickLine(key, item2) {
    console.log(item2);
    console.log(new Date().getTime());

    for (var i = 0; i < this.ishowerer.length; i++) {
      if (this.ishowerer[i] == true && i != key) {
        this.min++;
      }
    }
    if (this.min == 0) {
      this.ishowerer[key] = true;
      this.min = 0;
      if (item2) {
        this.jsq = setInterval(() => {
          // console.log(new Date().getTime() - item2);
          this.sfmtime = this.timeof(new Date().getTime() - item2 * 1000);
        }, 1000);
      } else {
        this.sfmtime = "00:00:00"
      }
    } else {
      this.ishowerer[key] = false;
      this.min = 0;
    }
    // console.log(this.ishowerer);

  }

  //开始计时
  start(item, key) {

    if (this.sjkg == false) {
      this.sjkg = true;
      if (this.sfmtime == "00:00:00") {
        this.axios.axiosPost("UpdateUnionOrder", {
          unionorder: item.union_order,
          name: "priority",
          newValue: new Date().getTime() / 1000,
        }).then((data) => {
          console.log(data);
          this.tempData[key].priority = new Date().getTime() / 1000
          this.clickLine(key, item.priority)
        })
      } else {
        alert("已經開始計時了")
      }
    } else {
      alert("已經開始計時，請勿重復操作")
    }
    // console.log(key)
    // this.btnStop[key] = true;
    // this.btnStart[key] = false;
    // console.log('00000000000000 \n', this.btnStart)
    // // this.setTime();
    // // timeIndex = 0;
    // console.log(item.sheji_shijian)
    // this.value = setInterval(setTime, 1000);
  }

  //结束计时
  end(item, key) {
    if (item.priority || this.sfmtime != "00:00:00") {
      clearInterval(this.jsq);
      this.ishowerer[key] = false;
      this.min = -1;
      this.sjkg = false;
      this.axios
        .axiosPost("AddWorkTime", {
          unionorder: item.union_order,
          endtime: new Date().getTime(),
          stage: 0,
        })
        .then((data) => {
          console.log(data);
          if (data["result"] === "ok") {
            console.log(this.tempData[key]);
            this.tempData[key].priority = "";
            console.log("真棒");
            this.sfmtime = "00:00:00";
            this.getAllData();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      alert("此工單未開始計時")
    }

    // this.btnStart[key] = false;
    // this.btnStop[key] = true;
    // // debugger
    // if (item.sheji_shijian === '') {
    //   item.sheji_shijian = 0;
    //   this.totalTime = item.sheji_shijian;
    // } else {
    //   this.totalTime = item.sheji_shijian;
    // }
    // console.log(this.totalTime)
    // // debugger
    // console.log(item, document.getElementsByClassName('sp')[0].innerHTML)
    // this.time = document.getElementsByClassName('sp')[0].innerHTML;
    // var hour = this.time.split(':')[0];
    // var min = this.time.split(':')[1];
    // var sec = this.time.split(':')[2];
    // var s;
    // s = Number(hour * 3600) + Number(min * 60) + Number(sec);
    // // var total;
    // // total =  parseInt(this.totalTime) + s;
    // // console.log(total,parseInt(this.totalTime))
    // this.recordRowClick = -1;
    // clearInterval(this.value);
    // this.value = null;

    // console.log('11111111111\n', this.isShow)
  }
  timeof(data) {
    var s;
    var hours: number;
    // hours=parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    hours = parseInt(
      ((data % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString()
    );
    // parseInt((1000 % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    // console.log(hours);
    var minutes = parseInt(
      ((data % (1000 * 60 * 60)) / (1000 * 60)).toString()
    );
    var seconds = parseInt(((data % (1000 * 60)) / 1000).toString());
    s =
      (hours < 10 ? "0" + hours : hours) +
      ":" +
      (minutes < 10 ? "0" + minutes : minutes) +
      ":" +
      (seconds < 10 ? "0" + seconds : seconds);
    // console.log(s);
    return s;
  }

  //结束页面生命周期
  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    clearInterval(this.jsq);
  }
  bzclick(name) {
    console.log(name);
    console.log(this.dlyy);
    this.dlyysz = [];
    for (var i = 0; i < this.dlyy.length; i++) {
      if (this.dlyy[i].show == true) {
        this.dlyysz.push(this.dlyy[i].name);
      }
    }
    this.dlyynr = this.dlyysz.join(",");
    console.log(this.dlyynr);
  }
}

//计时器
// function setTime() {
// hour = Math.floor(timeIndex / 3600);
// minutes = Math.floor((timeIndex - hour * 3600) / 60);
// seconds = timeIndex - hour * 3600 - minutes * 60;
// hour = hour < 10 ? "0" + hour : hour;
// minutes = minutes < 10 ? "0" + minutes : minutes;
// seconds = seconds < 10 ? "0" + seconds : seconds;
// console.log(hour, minutes, seconds)
// this.time = hour + ":" + minutes + ":" + seconds;
// timeIndex = timeIndex + 1;
// document.getElementsByClassName('sp')[0].innerHTML = this.time.toString();
// }
